<?php
namespace app\util;

use Exception;
use mysqli;

/**
 *
 */
class BackupMySQL {
    private $DB_HOST = '127.0.0.1'; // 数据库主机名
    private $DB_USER = 'root'; // 数据库用户名
    private $DB_PASS = 'root'; // 数据库密码
    private $DB_NAME = 'bishe'; // 数据库名
    private $backup_path = '../sql/'; // 备份文件保存路径

    function __construct($db_host,$db_user,$db_pass,$db_name,$backup_path = ''){
        $this->DB_HOST = $db_host;
        $this->DB_USER = $db_user;
        $this->DB_PASS = $db_pass;
        $this->DB_NAME = $db_name;
        if($backup_path) $this->backup_path = $backup_path;
        if (!file_exists($this->backup_path)) {
            mkdir($this->backup_path, 0777, true);
        }
    }

    // 备份数据库
    function backup(){
        $mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
        if(mysqli_connect_errno()){
            throw new Exception("Connect failed: ".mysqli_connect_error());
        }
        $mysqli->query("set names utf8");
        $tables = array();
        $result = $mysqli->query("show tables");
        while($row = $result->fetch_row()){
            $tables[] = $row[0];
        }
        $mysqli->query("SET FOREIGN_KEY_CHECKS=0");
        $sql = '';
        foreach($tables as $table){
            $result = $mysqli->query("select * from ".$table);
            if (!$result) continue;
            $num_fileds = $result->field_count;
            $num_rows = $mysqli->affected_rows;
            $sql .= 'DROP TABLE IF EXISTS '.$table.';';
            $mysql_query = $mysqli->query('show create table '.$table);
            if (empty($mysql_query)) {
                continue;
            }
            $row2 = $mysql_query->fetch_row();
            $sql .= "\n\n".$row2[1].";\n\n";
            for($i = 0; $i < $num_rows; $i++){
                $row = $result->fetch_row();
                $sql .= "INSERT INTO ".$table." VALUES(";
                for($j = 0; $j < $num_fileds; $j++){
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = preg_replace("/\n/i","\\n",$row[$j]);
                    if(isset($row[$j])){
                        $sql .= '"'.$row[$j].'"';
                    }
                    else{
                        $sql.= '""';
                    }
                    if($j < ($num_fileds - 1)){
                        $sql .= ',';
                    }
                }
                $sql .= ");\n";
            }
            $sql .= "\n\n\n";
        }
        $mysqli->query("SET FOREIGN_KEY_CHECKS=1");
        $filename = $this->backup_path.date('Y-m-d-H-i-s').".sql";
        mysqli_close($mysqli);
        if(file_put_contents($filename, $sql)){
            return true;
        } else {
            return false;
        }
    }
}